﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace VSM
{
    public partial class ForecastsPO : System.Web.UI.Page
    {
        private static GeneralFunctions GF = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("Login.aspx");
            }
            
            if(!IsPostBack)
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());

                hdnDocEntry.Value = Request.QueryString["DocEntry"];
                hdnPODate.Value = Request.QueryString["PODate"];
                hdnStatus.Value = Request.QueryString["Status"];

                DataTable tblFPO = (DataTable)Session["FPOTable"];
                DateTime dtPO = Utils.AppConstants.ConvertToDate(hdnPODate.Value);

                DateTime dt1 = dtPO.AddMonths(3);
                DateTime dt2 = dtPO.AddMonths(4);
                DateTime dt3 = dtPO.AddMonths(5);
                DateTime dt4 = dtPO.AddMonths(6);
                //
                grvFCPO.Columns[5].HeaderText = dt1.ToString("MMM., yyyy");
                grvFCPO.Columns[6].HeaderText = dt2.ToString("MMM., yyyy");
                grvFCPO.Columns[7].HeaderText = dt3.ToString("MMM., yyyy");
                grvFCPO.Columns[8].HeaderText = dt4.ToString("MMM., yyyy");
                if (tblFPO == null)
                {
                    tblFPO = new DataTable("tbl_ForecastPO");
                    tblFPO.Columns.Add("No", typeof(System.Int32));
                    tblFPO.Columns.Add("DocEntry", typeof(System.Int32));
                    tblFPO.Columns.Add("Model", typeof(System.String));
                    tblFPO.Columns.Add("Product", typeof(System.String));
                    tblFPO.Columns.Add("Qty1", typeof(System.Double));
                    tblFPO.Columns.Add("Qty2", typeof(System.Double));
                    tblFPO.Columns.Add("Qty3", typeof(System.Double));
                    tblFPO.Columns.Add("Qty4", typeof(System.Double));
                    tblFPO.Columns.Add("internal_id");
                }
                BindFCPO(tblFPO.Copy());
                if (hdnStatus.Value.Equals("C"))
                {
                    btnAccept.Enabled = false;
                    btnAddItems.Enabled = false;
                }
            }
        }

        protected void grvFCPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                if (this.hdnStatus.Value == "C") // || this.hdnIsCreatedSO.Value.Equals("true")
                {
                    DropDownList ddlModel = (DropDownList)myRow.FindControl("ddlModel");
                    DropDownList ddlProduct = (DropDownList)myRow.FindControl("ddlProduct");
                    //
                    TextBox txtQty1 = (TextBox)myRow.FindControl("txtQty1");
                    TextBox txtQty2 = (TextBox)myRow.FindControl("txtQty2");
                    TextBox txtQty3 = (TextBox)myRow.FindControl("txtQty3");
                    TextBox txtQty4 = (TextBox)myRow.FindControl("txtQty4");
                    //
                    LinkButton lnkDelete = (LinkButton)myRow.FindControl("lnkDelete");
                    if (lnkDelete != null) lnkDelete.Enabled = false;

                    if (txtQty1 != null)
                    {
                        txtQty1.ReadOnly = true;
                        txtQty1.BackColor = System.Drawing.Color.Transparent;
                        txtQty1.BorderStyle = BorderStyle.None;
                    }
                    if (txtQty2 != null)
                    {
                        txtQty2.ReadOnly = true;
                        txtQty2.BackColor = System.Drawing.Color.Transparent;
                        txtQty2.BorderStyle = BorderStyle.None;
                    }
                    if (txtQty3 != null)
                    {
                        txtQty3.ReadOnly = true;
                        txtQty3.BackColor = System.Drawing.Color.Transparent;
                        txtQty3.BorderStyle = BorderStyle.None;
                    }

                    if (txtQty4 != null)
                    {
                        txtQty4.ReadOnly = true;
                        txtQty4.BackColor = System.Drawing.Color.Transparent;
                        txtQty4.BorderStyle = BorderStyle.None;
                    }

                    if (ddlModel != null)
                    {
                        ddlModel.Enabled = false;
                        ddlModel.BackColor = System.Drawing.Color.Transparent;
                        ddlModel.BorderStyle = BorderStyle.None;
                    }

                    if (ddlProduct != null)
                    {
                        ddlProduct.Enabled = false;
                        ddlProduct.BackColor = System.Drawing.Color.Transparent;
                        ddlProduct.BorderStyle = BorderStyle.None;
                    }
                }

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grdFCPO_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                    e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)"); 
                    e.Row.Attributes["style"] = "cursor:pointer";
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    // Load Model
                    DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                    HiddenField hdnModel = (HiddenField)e.Row.FindControl("hdnModel");
                    if (ddlModel != null)
                    {
                        ddlModel.DataSource = GF.GetModelList(dbType);
                        ddlModel.DataValueField = "Code";
                        ddlModel.DataTextField = "Name";
                        ddlModel.DataBind();
                        ddlModel.Items.Insert(0, "");
                        if (hdnModel != null) ddlModel.SelectedValue = hdnModel.Value;
                    }
                    // Load Product
                    DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                    if (ddlProduct != null)
                    {
                        ddlProduct.DataSource = GF.GetProductByModel(dbType, hdnModel.Value);
                        ddlProduct.DataValueField = "Code";
                        ddlProduct.DataTextField = "Name";
                        ddlProduct.DataBind();
                        ddlProduct.Items.Insert(0, "");
                        HiddenField hdnProduct = (HiddenField)e.Row.FindControl("hdnProduct");
                        if (hdnProduct != null) ddlProduct.SelectedValue = hdnProduct.Value;
                    }
                }

            }
            catch (Exception ex)
            {

            }
        }

        protected void grdFCPO_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            DataTable tblFCPO = (DataTable)Session["FCPOTable"];
            this.grvFCPO.PageIndex = e.NewPageIndex;
            BindFCPO(tblFCPO);
        }

        protected void btnAccept_Click(object sender, EventArgs e)
        {
            try
            {
                //GridViewRow selectedRow = this.grvFCPO.SelectedRow;
                //if (selectedRow == null) return;
                //Session["ChosenFCPO"] = selectedRow;
                Session["FPOTable"] = (DataTable)Session["FCPOTable"];
                Session["FCPOTable"] = null;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "OK", "Main.okDialogClick('SelectFCPO');", true);
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void BindFCPO(DataTable tblFCPO)
        {
            Session["FCPOTable"] = tblFCPO;
            this.grvFCPO.DataSource = tblFCPO;
            this.grvFCPO.DataBind();
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tbFCPO = (DataTable)Session["FCPOTable"];
            DataRow rowNew = tbFCPO.NewRow();
            rowNew["No"] = (tbFCPO.Rows.Count + 1).ToString();
            rowNew["DocEntry"] = string.IsNullOrEmpty(hdnDocEntry.Value) ? "0" : hdnDocEntry.Value;
            rowNew["Model"] =
            rowNew["Product"] = string.Empty;
            rowNew["Qty1"] = 0;
            rowNew["Qty2"] = 0;
            rowNew["Qty3"] = 0;
            rowNew["Qty4"] = 0;
            tbFCPO.Rows.Add(rowNew);
            BindFCPO(tbFCPO);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["FCPOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString())) dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                        }
                        tb.Rows.Remove(rupdate[0]);
                        int liNo = 1;
                        foreach (DataRow dr in tb.Rows) // reset detail No. line
                        {
                            dr["No"] = liNo;
                            liNo++;
                        }
                    }
                    this.grvFCPO.EditIndex = -1;
                   BindFCPO(tb);
                }
            }
            catch (Exception ex)
            {
                
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtQty1_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQty1 = (TextBox)row.FindControl("txtQty1");
                if (txtQty1.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQty1.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["FCPOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0) rupdate[0]["Qty1"] = txtQty1.Text;
                }

                this.grvFCPO.EditIndex = -1;
                BindFCPO(tb);
            }
            catch (Exception ex)
            {
                
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtQty2_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQty2 = (TextBox)row.FindControl("txtQty2");
                if (txtQty2.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQty2.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["FCPOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0) rupdate[0]["Qty2"] = txtQty2.Text;
                }

                this.grvFCPO.EditIndex = -1;
                BindFCPO(tb);
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtQty3_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQty3 = (TextBox)row.FindControl("txtQty3");
                if (txtQty3.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQty3.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["FCPOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0) rupdate[0]["Qty3"] = txtQty3.Text;
                }

                this.grvFCPO.EditIndex = -1;
                BindFCPO(tb);
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtQty4_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQty4 = (TextBox)row.FindControl("txtQty4");
                if (txtQty4.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQty4.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["FCPOTable"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0) rupdate[0]["Qty4"] = txtQty4.Text;
                }

                this.grvFCPO.EditIndex = -1;
                BindFCPO(tb);
            }
            catch (Exception ex)
            {

            }
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }

                HiddenField hdnModel = (HiddenField)row.FindControl("hdnModel");
                hdnModel.Value = ddlModel.SelectedValue;
                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");

                    HiddenField hdnProduct = (HiddenField)row.FindControl("hdnProduct");
                    hdnProduct.Value = ddlProduct.SelectedValue;
                    SetItem(row);
                }
            }
            catch (Exception ex)
            {

            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                HiddenField hdnProduct = (HiddenField)row.FindControl("hdnProduct");
                hdnProduct.Value = ddlProduct.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {

            }
        }

        private void SetItem(GridViewRow row)
        {
            DataTable tblFCPO = (DataTable)Session["FCPOTable"];
            Label lblNo = (Label)row.FindControl("lblNo");
            DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
            DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
            //
            if (ddlModel != null && ddlProduct != null )
            {
                DataRow[] rowUpdate = null;
                rowUpdate = tblFCPO.Select("No=" + lblNo.Text);

                rowUpdate[0]["DocEntry"] = string.IsNullOrEmpty(hdnDocEntry.Value) ? "0" : hdnDocEntry.Value;
                rowUpdate[0]["Model"] = ddlModel.SelectedValue;
                rowUpdate[0]["Product"] = ddlProduct.SelectedValue;
                rowUpdate[0]["Qty1"] = 0;
                rowUpdate[0]["Qty1"] = 0;
                rowUpdate[0]["Qty1"] = 0;
                rowUpdate[0]["Qty1"] = 0;
                //                
                BindFCPO(tblFCPO);
            }
        }

    }
}